<template>
  <icon-github :size="size" @click="handleAuth" class="cursor-pointer"/>
</template>

<script lang="ts" setup>
import {ref} from 'vue'
import {getClientId} from "@/api/login";
import {Message} from "@arco-design/web-vue";

const emits = defineEmits(['updateCode'])

withDefaults(
    defineProps<{
      size?: number
    }>(), {
      size: 14
    }
)
const client_id = ref()

function handleAuth() {
  if (!client_id.value) {
    Message.warning('client_id 获取失败')
    return
  }
  const childWindow = window.open(`https://github.com/login/oauth/authorize?client_id=${client_id.value}`, 'o_author_window', 'height=500,width=500')
  window.addEventListener('message', (event) => {
    if (event.origin === location.origin && typeof event.data.accessCode === 'string') {
      setTimeout(() => {
        emits('updateCode', event.data.accessCode)
        childWindow?.close()
      }, 1000)
    }
  });
}

getClientId().then(data => {
  client_id.value = data.data
})
</script>